package com.wangyk.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter
{

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean()
        throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        http.authorizeRequests().anyRequest().authenticated().and() //开启默认登录页面
            .formLogin() //默认登录页面
            .loginPage("/login") //默认登录成功跳转页面
            .defaultSuccessUrl("/chat").permitAll().and() //设置注销
            .logout().permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
        throws Exception
    {
        auth.inMemoryAuthentication()
            .passwordEncoder(passwordEncoder())
            .withUser("test")
            .password(passwordEncoder().encode("123456"))
            .roles("USER")
            .and()
            .withUser("kai")
            .password(passwordEncoder().encode("222"))
            .roles("USER");
    }

}
